﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" :rules="formRules" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="申请单编号" tooltip="系统自动生成" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注说明" tooltip="补充说明（选填）" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>续签信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '续签员工为必填项', trigger: 'change' }]"
							>
								<template #label>
									<WtmLabelTooltip label="续签员工" tooltip="选择申请续签的员工" />
								</template>
								<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" @change="onPersonSelected" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_PersonContractId_FormItem" prop="Entity.PersonContractId">
								<template #label>
									<WtmLabelTooltip label="原合同" tooltip="请选择关联的原合同" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.PersonContractId" clearable class="width100">
									<el-option v-for="item in stateData.AllSysPersonContracts" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EmploymentType_FormItem"
								prop="Entity.EmploymentType"
								:rules="[{ required: true, message: '用工形式为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="用工形式" tooltip="用工形式" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EmploymentType" clearable class="width100">
									<el-option key="全职" value="全职" label="全职"></el-option>
									<el-option key="兼职" value="兼职" label="兼职"></el-option>
									<el-option key="实习" value="实习" label="实习"></el-option>
									<el-option key="外包" value="外包" label="外包"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ContractType_FormItem"
								prop="Entity.ContractType"
								:rules="[{ required: true, message: '合同类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="合同类型" tooltip="合同类型" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.ContractType" clearable class="width100">
									<el-option key="固定期限" value="固定期限" label="固定期限"></el-option>
									<el-option key="无固定期限" value="无固定期限" label="无固定期限"></el-option>
									<el-option key="项目合同" value="项目合同" label="项目合同"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>合同信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ContractNo_FormItem"
								prop="Entity.ContractNo"
								:rules="[{ required: true, message: '合同编号为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="合同编号" tooltip="新合同编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.ContractNo" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_SignDate_FormItem"
								prop="Entity.SignDate"
								:rules="[{ required: true, message: '签订日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="签订日期" tooltip="新合同签订日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.SignDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ExpireDate_FormItem"
								prop="Entity.ExpireDate"
								:rules="[{ required: true, message: '到期日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="到期日期" tooltip="新合同到期日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.ExpireDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>附件信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="SelectedContractFilesIds_FormItem" prop="SelectedContractFilesIds">
								<template #label>
									<WtmLabelTooltip label="合同附件" tooltip="上传新的合同附件" />
								</template>
								<wtm-upload-file
									v-model="stateData.vmModel.SelectedContractFilesIds"
									clearable
									class="width100"
									:multi="true"
									:limit="10"
								></wtm-upload-file>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<wtm-org-selector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								prop="Entity.OrgId"
								:auth="false"
								:disabled="true"
								placeholder="选取人员后带入"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<wtm-dept-selector v-model="stateData.vmModel.Entity.GroupId" label="所属部门" prop="Entity.GroupId" :disabled="true" :auth="false" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrRenewRequestBillApi as api } from '/@/views/hr/syshrrenewrequestbill/api';
import other from '/@/utils/other';
import { ISysHrRenewRequestBillVm } from '/@/views/hr/syshrrenewrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { useUserInfo } from '/@/stores/userInfo';
import { getCurrentUserMainGroupId } from '/@/utils/userGroup';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const API_ENDPOINTS = {
	PERSON_CONTRACTS: '/api/SysHrRenewRequestBill/GetSysPersonContracts',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);

// 获取用户信息store
const userInfoStore = useUserInfo();

// 表单验证规则
const formRules = {
	'Entity.StaffNo': [{ required: true, message: '请输入员工工号', trigger: 'blur' }],
	'Entity.Name': [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
	'Entity.EmploymentType': [{ required: true, message: '请选择用工形式', trigger: 'change' }],
	'Entity.ContractType': [{ required: true, message: '请选择合同类型', trigger: 'change' }],
	'Entity.GroupId': [{ required: true, message: '请选择所属部门', trigger: 'change' }],
};

const stateData = reactive<IViewModel<ISysHrRenewRequestBillVm>>({
	vmModel: {
		Entity: {
			PersonId: null,
			StaffNo: null,
			Name: null,
			PersonContractId: null,
			EmploymentType: null,
			ContractType: null,
			ContractNo: null,
			SignDate: null,
			ExpireDate: null,
			ContractFiles: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			OrgId: null,
		},
		ActionName: null,
		IsMyApprove: null,
		SelectedContractFilesIds: null,
		Remark: null,
	},

	AllSysPersonContracts: [] as any[],
});

// 计算属性
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

const canSubmit = computed(() => hasEntityId.value && hasSavedOnce.value);

// 统一的成功处理函数
const handleSuccess = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
		// 保存后不关闭弹窗，更新实体ID
		if (response?.Entity?.ID) {
			stateData.vmModel.Entity = response.Entity;
		} else if (response?.ID) {
			(stateData.vmModel.Entity as any).ID = response.ID;
		}
		hasSavedOnce.value = true;
	}

	loading.value = false;
	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleSuccess(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false // 保存后不关闭弹窗
	);
};

// 提交
const onSubmit = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true // 提交后关闭弹窗
	);
};

// 人员选择变化处理
const onPersonSelected = (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = '';
		stateData.vmModel.Entity.Name = '';
		stateData.vmModel.Entity.OrgId = '';
		stateData.vmModel.Entity.GroupId = '';
	}
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		(stateData.vmModel.Entity as any).ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [personContracts, billCode] = await Promise.allSettled([other.getSelectList(API_ENDPOINTS.PERSON_CONTRACTS, [], false), api().getBillCode()]);

	// 处理成功的结果
	if (personContracts.status === 'fulfilled') stateData.AllSysPersonContracts = personContracts.value;
	if (billCode.status === 'fulfilled') stateData.vmModel.Entity.BillCode = billCode.value.Data as string;

	// 设置默认部门为当前用户的主要部门
	if (!stateData.vmModel.Entity.GroupId) {
		stateData.vmModel.Entity.GroupId = getCurrentUserMainGroupId();
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 确保用户信息已加载
		await userInfoStore.setUserInfos();
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value, // 未保存过时显示保存按钮
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value, // 已保存且有ID时显示提交按钮
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
